package com.youan.log.modules.audit.service.impl;

import com.youan.log.common.bean.ValidateResult;
import com.youan.log.modules.audit.dataimport.ImportDataThread;
import com.youan.log.modules.audit.dataimport.PreImportValidate;
import com.youan.log.modules.audit.dataimport.TaskDataGetter;
import com.youan.log.modules.audit.dataimport.bean.ImportTaskKey;
import com.youan.log.modules.audit.dataimport.bean.TaskData;
import com.youan.log.modules.audit.entity.ImportRecord;
import com.youan.log.modules.audit.service.IImportRecordService;
import com.youan.log.modules.audit.service.IImportService;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springblade.common.cache.ParamCache;
import org.springblade.core.log.exception.ServiceException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDateTime;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.stream.Collectors;

@Service
public class ImportServiceImpl implements IImportService {
    @Autowired
    private IImportRecordService importRecordService;

    @Override
    public void startImport(List<String> importDates) {
        List<ImportRecord> runningRecords = importRecordService.getAllRunningRecords();
        if(CollectionUtils.isNotEmpty(runningRecords)) {
            throw new ServiceException("无法开启新的数据导入任务: 当前存在未完成任务!!");
        }

        String num = ParamCache.getValue("import_thread_num");
        if(StringUtils.isBlank(num)) {
            throw new ServiceException("无法开启任务，系统中未配置导入线程数参数:[import_thread_num]");
        }
        int threadNum = Integer.parseInt(num);

        LocalDateTime taskStartTime = LocalDateTime.now();
        // 进行由小到大的排序
        Collections.sort(importDates);
        List<Long> startRecordIds = importDates
                .stream()
                .map(date -> {
                    ImportRecord importRecord = new ImportRecord();
                    importRecord.setTaskStartTime(taskStartTime);
                    importRecord.setTaskStatus(ImportTaskKey.THREAD_TASK_STATUS_READY);
                    importRecord.setDate(date);
                    return importRecord;
                })
                .map(item -> {
                    importRecordService.save(item);
                    return item.getId();
                })
                .collect(Collectors.toList());

        ExecutorService executorService = Executors.newFixedThreadPool(threadNum);
        for (Long importRecordId : startRecordIds) {
            executorService.execute(new ImportDataThread(importRecordId));
        }
    }

    @Override
    public List<TaskData> getDataHasImportedTaskData() {
        TaskDataGetter getter = new TaskDataGetter();
        List<TaskData> hasImportedTaskData = getter.getHasImportedTaskData();
        return hasImportedTaskData;
    }

    @Override
    public List<TaskData> getCanImportTaskData() {
        TaskDataGetter getter = new TaskDataGetter();
        List<TaskData> canImportedTaskData = getter.getCanImportedTaskData();
        return canImportedTaskData;
    }



    @Override
    public void deleteTaskDataFile(String date) {
        PreImportValidate validate = new PreImportValidate();
        ValidateResult validateResult = validate.validateImportFolder();
        if(!validateResult.isPass()) {
            throw new ServiceException(validateResult.getMessage());
        }

        String workSpace = ParamCache.getValue("data_import_path");
        try {
            Path path = Paths.get(workSpace, date, date+"_sd_s_region.txt");
            Files.deleteIfExists(path);

            path = Paths.get(workSpace, date, date+"_sd_d_region.txt");
            Files.deleteIfExists(path);

            path = Paths.get(workSpace, date, date);
            Files.deleteIfExists(path);
        } catch (IOException ioException) {
            ioException.printStackTrace();
        }

    }
}
